package com.sharemarking.wa.platform.service.OrderDelayQueue;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author dxy
 */
public class OrderDelay implements Delayed {
    private int id;
    // 延迟时长，这个是必须的属性因为要按照这个判断延时时长。
    private long executeTime;

    public int getId() {
        return id;
    }


    public long getExecuteTime() {
        return executeTime;
    }

    public void setExecuteTime(long executeTime) {
        this.executeTime = executeTime;
    }

    public OrderDelay(int id,long delayTime) {
        this.id = id;
        this.executeTime = TimeUnit.NANOSECONDS.convert(delayTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    public OrderDelay(int id) {
        this.id = id;
    }

    // 自定义实现比较方法返回 1 0 -1三个参数
    @Override
    public int compareTo(Delayed delayed) {
        OrderDelay msg = (OrderDelay) delayed;
        return this.executeTime > msg.executeTime ? 1
                : this.executeTime < msg.executeTime ? -1 : 0;
    }

    // 延迟任务是否到时就是按照这个方法判断如果返回的是负数则说明到期否则还没到期
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.executeTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof OrderDelay)) {
            return false;
        }
        OrderDelay that = (OrderDelay) o;
        return getId() == that.getId();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId());
    }
}
